package cn.knet.sp.ncrm.common.utils;

import java.text.SimpleDateFormat;

/**
* 获取主键ID，使用时间+计数器方式实现
* @author 
*
*/
public class IdUtils {

public static IdUtils instance = null;

private static final long ONE_STEP = 100;
private static String lastTime = new SimpleDateFormat("yyyyMMddHHmmssS").format(System.currentTimeMillis());
private static short count = 0;

/**
* 获取单例对象
* @return
*/
public synchronized static IdUtils getInstanse(){
   if(instance == null){
    instance = new IdUtils();
   }
   return instance;
}

private IdUtils(){
}
/**
* 根据对象获取表主键
* @return
*/
public synchronized String getUID(String prefix){
   try{
    if (count == ONE_STEP) {
     boolean done = false;
     while (!done) {
         String now = new SimpleDateFormat("yyyyMMddHHmmssS").format(System.currentTimeMillis());
      if (lastTime.equalsIgnoreCase(now)) {
       try {
        Thread.sleep(1);
       } catch (InterruptedException e) {
       }
       continue;
      } else {
       lastTime = now;
       count = 0;
       done = true;
      }
     }
    }
   }catch(Exception e){
    e.printStackTrace();
   }
   String result = prefix + lastTime + (count++);
   return result;
}

public static void main(String[] args) {
	System.out.println(IdUtils.getInstanse().getUID("KNET"));
    System.out.println(System.currentTimeMillis());
}

}